#include "../common/etcd.hpp"
#include "main.pb.h"
#include "../common/brpc.hpp"
#include "gflags/gflags.h"
#include <thread>

DEFINE_bool(run_mode, false, "程序的运行模式，false-调试；true-发布");
DEFINE_string(log_file, "", "发布模式下，用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下，用于指定日志输出等级");

DEFINE_string(etcd_host, "127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(call_service, "/service/echo", "调用的服务目录");


void callback(brpc::Controller* cntl, example::EchoResponse* rsp)
{
    //用智能指针管理，防止忘记释放造成的资源泄露
    std::unique_ptr<brpc::Controller> cntl_guard(cntl);
    std::unique_ptr<example::EchoResponse> rsp_guard(rsp);
    if(cntl->Failed() == true)
    {
        std::cout << "Rpc 调用失败！" << cntl->ErrorText() << std::endl;
        // delete cntl;
        // delete rsp;
        return;
    }
    std::cout << rsp->message() << std::endl;
    // delete cntl;
    // delete rsp;
}


int main(int argc, char* argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    ChatSystem::InitLogger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    //客户端改造思想：
    //1. 先构造Rpc整体的服务管理信道类
    ChatSystem::ServiceManager::ptr service_manager = std::make_shared<ChatSystem::ServiceManager>();
    service_manager->declared(FLAGS_call_service);  //设置需要关心的服务
    auto put_cb = std::bind(&ChatSystem::ServiceManager::onServiceOnline, service_manager.get(), std::placeholders::_1, std::placeholders::_2);
    auto del_cb = std::bind(&ChatSystem::ServiceManager::onServiceOffline, service_manager.get(), std::placeholders::_1, std::placeholders::_2);
    //2. 构造服务发现对象 
    ChatSystem::Discovery::ptr dclient = std::make_shared<ChatSystem::Discovery>(FLAGS_etcd_host, FLAGS_base_service, put_cb, del_cb);
    
    while(1)
    {
        //3. 通过Rpc信道管理对象，获取提供Echo服务的信道
        auto channel = service_manager->choose(FLAGS_call_service);
        if(!channel)
        {
            return -1;
        }
        //4. 发起Echo Rpc调用
        // 2.实例化pb中的EchoService_Stub类对象；
        example::EchoService_Stub stub(channel.get());
        // 3.发起rpc请求，获取响应进行处理；
        brpc::Controller* cntl = new brpc::Controller;
        example::EchoRequest req;
        req.set_message("你好呀，Echo");

        example::EchoResponse* rsp = new example::EchoResponse;

        google::protobuf::Closure* closure = google::protobuf::NewCallback(callback, cntl, rsp);
        stub.Echo(cntl, &req, rsp, closure);    //rpc异步调用
        std::cout << "Rpc异步调用结束!" << std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
    
    return 0;
}